﻿using System;
using System.Collections.Generic;
using System.Text;

namespace XinYiOffice.Common
{
    /// <summary>
    /// 日期扩展操作类,提供日期间隔对比
    /// </summary>
    public static class DateTimeTools
    {
        /// <summary>
        /// 计算日期间隔
        /// </summary>
        /// <param name="d1">要参与计算的其中一个日期</param>
        /// <param name="d2">要参与计算的另一个日期</param>
        /// <param name="drf">决定返回值形式的枚举</param>
        /// <returns>一个代表年月日的int数组，具体数组长度与枚举参数drf有关</returns>
        public static int[] Diff(DateTime d1, DateTime d2, DateTimeDiffFormat drf)
        {
            #region 数据初始化
            DateTime max;
            DateTime min;
            int year;
            int month;
            int tempYear, tempMonth;
            if (d1 > d2)
            {
                max = d1;
                min = d2;
            }
            else
            {
                max = d2;
                min = d1;
            }
            tempYear = max.Year;
            tempMonth = max.Month;
            if (max.Month < min.Month)
            {
                tempYear--;
                tempMonth = tempMonth + 12;
            }
            year = tempYear - min.Year;
            month = tempMonth - min.Month;
            #endregion
            #region 按条件计算
            if (drf == DateTimeDiffFormat.Day)
            {
                TimeSpan ts = max - min;
                return new int[] { ts.Days };
            }
            if (drf == DateTimeDiffFormat.Month)
            {
                return new int[] { month + year * 12 };
            }
            if (drf == DateTimeDiffFormat.Year)
            {
                return new int[] { year };
            }
            return new int[] { year, month };
            #endregion
        }

        /// <summary>
        /// 关于返回值形式的枚举
        /// </summary>
        public enum DateTimeDiffFormat
        {
            /// <summary>
            /// 年数和月数
            /// </summary>
            YearMonth,
            /// <summary>
            /// 年数
            /// </summary>
            Year,
            /// <summary>
            /// 月数
            /// </summary>
            Month,
            /// <summary>
            /// 天数
            /// </summary>
            Day,
        }
    }
}